import React, { useState } from "react";
import {
  Button,
  DatePicker,
  Space,
  Table,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";

const { Option } = Select;
const { confirm } = Modal;

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}

const initialData: DataType[] = [
  {
    key: "1",
    name: "张三",
    age: 32,
    address: "上海市浦东新区",
    tags: ["开发者", "前端"],
  },
  {
    key: "2",
    name: "李四",
    age: 42,
    address: "北京市朝阳区",
    tags: ["管理员"],
  },
  {
    key: "3",
    name: "王五",
    age: 32,
    address: "杭州市西湖区",
    tags: ["用户", "测试"],
  },
];

const AntdDemo: React.FC = () => {
  const [data, setData] = useState<DataType[]>(initialData);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingRecord, setEditingRecord] = useState<DataType | null>(null);
  const [form] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();

  const showAddModal = () => {
    setEditingRecord(null);
    form.resetFields();
    setIsModalOpen(true);
  };

  const showEditModal = (record: DataType) => {
    setEditingRecord(record);
    form.setFieldsValue(record);
    setIsModalOpen(true);
  };

  const handleDelete = (key: string) => {
    confirm({
      title: "确定要删除这条记录吗?",
      icon: <ExclamationCircleOutlined />,
      content: "删除后无法恢复",
      okText: "确认",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        setData(data.filter((item) => item.key !== key));
        messageApi.success("删除成功");
      },
    });
  };

  const handleModalOk = () => {
    form.validateFields().then((values) => {
      const newData = [...data];

      // 处理标签，将字符串转换为数组
      const formattedValues = {
        ...values,
        tags:
          typeof values.tags === "string"
            ? values.tags.split(",").map((tag: string) => tag.trim())
            : values.tags,
      };

      if (editingRecord) {
        // 编辑现有记录
        const index = newData.findIndex(
          (item) => item.key === editingRecord.key
        );
        newData[index] = { ...editingRecord, ...formattedValues };
        messageApi.success("更新成功");
      } else {
        // 添加新记录
        newData.push({
          key: `${newData.length + 1}`,
          ...formattedValues,
        });
        messageApi.success("添加成功");
      }

      setData(newData);
      setIsModalOpen(false);
    });
  };

  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
      render: (text: string) => <a>{text}</a>,
    },
    {
      title: "年龄",
      dataIndex: "age",
      key: "age",
    },
    {
      title: "住址",
      dataIndex: "address",
      key: "address",
    },
    {
      title: "标签",
      key: "tags",
      dataIndex: "tags",
      render: (tags: string[]) => (
        <>
          {tags.map((tag) => {
            let color = tag.length > 5 ? "geekblue" : "green";
            if (tag === "管理员") {
              color = "volcano";
            }
            return (
              <Tag color={color} key={tag}>
                {tag.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: DataType) => (
        <Space size="middle">
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => showEditModal(record)}
          />
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.key)}
          />
        </Space>
      ),
    },
  ];

  return (
    <div className="antd-demo">
      {contextHolder}
      <div className="demo-header" style={{ marginBottom: 16 }}>
        <Space>
          <h2>Ant Design 组件示例</h2>
          <DatePicker placeholder="选择日期" />
          <Button type="primary" icon={<PlusOutlined />} onClick={showAddModal}>
            添加数据
          </Button>
        </Space>
      </div>

      <Table columns={columns} dataSource={data} />

      <Modal
        title={editingRecord ? "编辑记录" : "添加记录"}
        open={isModalOpen}
        onOk={handleModalOk}
        onCancel={() => setIsModalOpen(false)}
        okText={editingRecord ? "保存" : "添加"}
        cancelText="取消"
      >
        <Form form={form} layout="vertical" name="record_form">
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: "请输入姓名" }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>

          <Form.Item
            name="age"
            label="年龄"
            rules={[{ required: true, message: "请输入年龄" }]}
          >
            <Input type="number" placeholder="请输入年龄" />
          </Form.Item>

          <Form.Item
            name="address"
            label="住址"
            rules={[{ required: true, message: "请输入住址" }]}
          >
            <Input placeholder="请输入住址" />
          </Form.Item>

          <Form.Item
            name="tags"
            label="标签"
            rules={[{ required: true, message: "请选择标签" }]}
          >
            <Select
              mode="tags"
              placeholder="请选择或输入标签"
              style={{ width: "100%" }}
            >
              <Option value="开发者">开发者</Option>
              <Option value="前端">前端</Option>
              <Option value="后端">后端</Option>
              <Option value="管理员">管理员</Option>
              <Option value="用户">用户</Option>
              <Option value="测试">测试</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AntdDemo;
